<template>
  <a-card title="Borrowing Info" :bordered="false">
    <!-- <a-space direction="vertical"> -->
    <a-col :span="8">
      <a-card hoverable style="width: 200px;margin-top:50px" :bordered="false">
        <template #cover>
          <img :src="bookInfo.cover"/>
        </template>
      </a-card>
    </a-col>
    <a-col :span="8">
      <a-card hoverable style="width: 500px;margin-top:50px" :bordered="false">
        <h2>评价：</h2>
        <template>
          <a-rate v-model="score" allow-half :tooltips="desc"/>
          <span class="ant-rate-text">{{ score }}</span>
        </template>
        <br><br>
        <a-popconfirm
            title="提交评分"
            @confirm="updateScore()"
            @cancel="cancel"
          >
            <a-button type="primary" :style="{ marginLeft: '8px' }" icon="el-icon-edit">提交评价</a-button>
        </a-popconfirm>
      </a-card>
    </a-col>


    <template>
      <a-descriptions size="default" bordered 
      style="margin-top:50px"
      >
        <a-descriptions-item label="book name ">{{
          this.bookInfo.bookName
        }}</a-descriptions-item>
        <a-descriptions-item label="borrowing id">{{
          borrowingDetail.borrowing_id
        }}</a-descriptions-item>

        <a-descriptions-item label="ISBN">{{
          borrowingDetail.ISBN
        }}</a-descriptions-item>

        <a-descriptions-item label="status">{{
          borrowingDetail.status
        }}</a-descriptions-item>

        <a-descriptions-item label="borrow time">{{
          borrowingDetail.borrow_time
        }}</a-descriptions-item>

        <a-descriptions-item label="due time">{{
          borrowingDetail.due_time
        }}</a-descriptions-item>
        <a-descriptions-item label="return time">{{
          borrowingDetail.return_time
        }}</a-descriptions-item>
        <a-descriptions-item label="fine">
          {{borrowingDetail.fine}}
        </a-descriptions-item>
      </a-descriptions>
    </template>

    <a-tooltip
      class="item"
      effect="dark"
      size="small"
      content="详情"
      placement="top"
      v-if="borrowingDetail.status === 0"
    >
      
      <a-popconfirm title="Are you sure to pay the fine?" @confirm="confirmPayment" @cancel="cancelPayment" v-if="showPaymentConfirm">
        <a-button type="primary" :style="{ top:'8px', marginLeft: '8px' }" icon="el-icon-edit">支付</a-button>
      </a-popconfirm>


      <div v-if="showQRCode">
        <p>请扫描二维码进行支付</p>
        <img src="../../assets/支付宝.png" alt="二维码">
        <a-button type="primary" @click="completePayment()">确认支付</a-button>
      </div>

      <div v-if="paymentCompleted">
        支付成功！
      </div>

      <a-alert
        v-if="showNoFineAlert"
        type="info"
        show-icon
        message="您不需要支付罚款">
      </a-alert>

      <!--<a-popconfirm title="Are you sure to pay the fine?" @confirm="payFine()" @cancel="cancel" v-if="borrowingDetail.fine > 0">
        <a-button type="primary" :style="{ top:'8px',marginLeft: '8px' }" icon="el-icon-edit">Pay</a-button>
      </a-popconfirm>-->
      
    </a-tooltip>
    <!-- </a-space> -->
  </a-card>
</template>

<script>
import { getAccessToken, getUserInfo } from "../../services/user";
import moment from 'moment'
export default {
  data() {
    return {
      score: 0.0,
      desc: ['Terrible', 'Bad', 'Normal', 'Good', 'Wonderful!'],
      borrowingDetail: [],
      book_cover: "null",
      book_name: "null",
      bookInfo: [],
      orderUrl: "https://1893791694056142.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/web-framework/express-app/createOrder",
      showPaymentConfirm: true, 
      showQRCode: false,         
      showNoFineAlert: false,
      paymentCompleted: false    
    };
  },
  created() {
    this.getBorrowingDetail(this.$route.params.id);
  },
  methods: {
    async getBorrowingDetail(borrowing_id) {
      // 获得借书详情
      let that = this;

      var myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());
      myHeaders.append("Content-Type", "application/json");

      var myInit = { method: "GET", headers: myHeaders };

      var myUrl =
        this.$global.BASE_URL +
        "/api/user/borrowing/detail?borrowing_id=" +
        borrowing_id;

      var myRequest = new Request(myUrl, myInit);

      await fetch(myRequest)
        .then((response) => response.json())
        .then(function (data) {
          console.log("borrowing_detail", data);
          that.borrowingDetail = data.data;
          var days = moment(that.borrowingDetail.due_time).diff(moment(that.borrowingDetail.borrow_time), 'days')
          if (days < 0) {
            that.borrowingDetail.fine = Math.abs(days)
          } else {
            that.borrowingDetail.fine = 0
          }
          that.borrowingDetail.borrow_time = moment(that.borrowingDetail.borrow_time).format("dddd, MMMM Do YYYY")
          that.borrowingDetail.due_time = moment(that.borrowingDetail.due_time).format("dddd, MMMM Do YYYY")
        })
        .catch((err) => console.log("Request Failed", err));
      console.log(this.borrowingDetail);

      // 获得图书详情
      var myHeaders2 = new Headers();
      myHeaders2.append("Content-Type", "application/json");
      myHeaders2.append("token", getAccessToken());

      var myInit2 = { method: "GET", headers: myHeaders2 };
      var myUrl2 = this.$global.BASE_URL + "/api/admin/book/detail?ISBN=" + this.borrowingDetail.ISBN;
      var myRequest2 = new Request(myUrl2, myInit2);
      
      await fetch(myRequest2)
        .then((response) => response.json())
        .then(function (data) {
          console.log("book_detail", data);
          that.book_name = data.data[0].bookName;
          that.book_cover = data.data[0].cover;
          that.bookInfo = data.data[0];
          console.log(data.data[0].score)
          that.score = data.data[0].score
        });
    },

    updateScore(){
      let score = this.score
      let borrowing_id = this.borrowingDetail.borrowing_id
      let ISBN = this.borrowingDetail.ISBN
      console.log(borrowing_id)
      

      let myHeaders = new Headers({ "Content-Type": "application/json" });
      myHeaders.append("token", getAccessToken());
      let requestoptions = {
        method: "GET",
        headers: myHeaders,
      };

      fetch(`${this.$global.BASE_URL}/api/user/borrowing/score?borrowing_id=${borrowing_id}&ISBN=${ISBN}&score=${score}`, requestoptions)
        .then((response) => response.json())
        .then((result) => {
          const {code, data, msg} = result;
          if(code == 0){
            this.$message.success("感谢您的评价！");
          }else{
            this.$message.error(msg);
          }
          console.log(result);
        });


    },


    confirmPayment() {
      // 用户点击支付按钮后显示二维码
      console.log(this.borrowingDetail.fine );
      if (this.borrowingDetail.fine > 0) {
        this.showPaymentConfirm = false;
        this.showQRCode = true;
        this.showNoFineAlert = false;
      } else {
        this.showPaymentConfirm = false;
        this.showNoFineAlert = true;
        this.showQRCode = false;
      }
      
    },
    cancelPayment() {
      
      this.showPaymentConfirm = false;
    },

    // completePayment(borrow_id) {
    //   let that = this;
    //   console.log(borrow_id);

    //   // 设置请求头
    //   var myHeaders = new Headers();
    //   myHeaders.append("token", getAccessToken());
    //   myHeaders.append("Content-Type", "application/json");

    //   // 构建请求参数
    //   var myInit = {
    //     method: "GET",
    //     headers: myHeaders,
    //   };

    //   // 拼接URL，包含查询参数borrow_id
    //   var myUrl = this.$global.BASE_URL + "/api/user/fine/pay?borrow_id=" + borrow_id;

    //   // 发起GET请求
    //   fetch(myUrl, myInit)
    //     .then((response) => response.json())
    //     .then(function (data) {
    //       console.log("payFine", data);
    //       if (data.code === 0) {
    //         that.$message.success("罚款支付成功！");
    //         setTimeout(function() {
    //         window.location.reload();
    //       }, 2000);
            
    //       } else {
    //         that.$message.error(data.msg);
    //       }
    //     })
    //     .catch((err) => console.log("Request Failed", err));
    // },



    // 归还图书
    returnBook(borrowing_id) {
      let that = this;
      console.log(borrowing_id);

      var myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());
      myHeaders.append("Content-Type", "application/json");

      var myBody = {
        borrowing_id: borrowing_id,
      };

      var myInit = {
        method: "POST",
        headers: myHeaders,
        body: JSON.stringify({ borrowing_id }),
      };

      var myUrl = this.$global.BASE_URL + "/api/borrowing/return";

      var myRequest = new Request(myUrl, myInit);

      fetch(myRequest)
        .then((response) => response.json())
        .then(function (data) {
          console.log("return", data);
          if (data.code === 0) {
            that.$message.success("return successfully!");
            that.updateReputation(10);
          } else {
            that.$message.error(data.msg);
          }
        })
        .catch((err) => console.log("Request Failed", err));
    },
    cancel() {
      // this.$message.error("Click on No");
    },
    // 续借图书
    renewBook(borrowing_id) {
      let that = this;
      console.log(borrowing_id);

      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      myHeaders.append("token", getAccessToken());

      var myBody = {
        borrowing_id: borrowing_id,
      };

      var myInit = {
        method: "POST",
        body: JSON.stringify(myBody),
        headers: myHeaders,
      };

      var myRequest = new Request(
        this.$global.BASE_URL + "/api/borrowing/renew",
        myInit
      );

      fetch(myRequest)
        .then((response) => response.json())
        .then(function (data) {
          console.log(data);
          if (data.code === 0) {
            that.$message.success("renew successfully!");
          } else {
            that.$message.error(data.msg);
          }
        })
        .catch((err) => console.log("Request Failed", err));
    },

    completePayment() {
      let that = this;
      console.log(this.borrowingDetail.borrowing_id);

      var myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());
      myHeaders.append("Content-Type", "application/json");

      var myBody = {
        borrow_id: this.borrowingDetail.borrowing_id,
        user_id: getUserInfo().user_id,
        amount: this.borrowingDetail.fine,
      };

      var myInit = {
        method: "POST",
        headers: myHeaders,
        body: JSON.stringify(myBody),
      };

      var myRequest = new Request(
        this.$global.BASE_URL + "/api/user/fine/pay",
        myInit
      );

      fetch(myRequest)
        .then((response) => response.json())
        .then(function (data) {
          console.log(data);
          if (data.code === 0) {
            that.$message.success("add fine successfully!");
          } else {
            that.$message.error(data.msg);
          }
        })
        .catch((err) => console.log("Request Failed", err));
    },


    async payFine() {
      let goodsName = `fine${this.borrowingDetail.borrowing_id}`
      let ISBN = this.borrowingDetail.ISBN;
      let book_id = this.borrowingDetail.book_id;
      let payName = getUserInfo().user_id;
      let count = 1;
      let price = this.borrowingDetail.fine;
      let cost = price;
      let that = this;
      await fetch(this.orderUrl, {
        method: "POST",
        "headers": {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        body: `payName=${payName}&goodsName=${goodsName}&price=${price}&count=${count}&cost=${cost}&ISBN=${ISBN}&book_id=${book_id}`
      })
        .then(response => response.text())
        .then(res => {
          document.querySelector('body').innerHTML = res;//这里的JSON.parse(res.data.data).responsePage是为了拿到上面所说的Form表单数据，因为我请求的接口是被封装过一层的，所以大家使用的时候将这里替换成实际拿到的Form表单数据就可以了
          const div = document.createElement('div') // 创建div
          div.innerHTML = res;//这里同上面所说的使用时将JSON.parse(res.data.data).responsePage替换为自己获取的Form表单数据
            // 将返回的form 放入div
          document.body.appendChild(div)
          console.log(11111, document.forms[0])
          document.forms[0].submit()
          // console.log(that.$root.$el.innerHTML)
        }) 
    }
  },
  updateReputation(change) {
    let that = this;
    let myHeaders = new Headers({"Content-Type": "application/json"});
    myHeaders.append("token", getAccessToken());
    let requestOptions = {
      method: "POST",
      headers: myHeaders,
      body: JSON.stringify({ change: change }),
    };

    const url = `${this.$global.BASE_URL}/api/user/profile/updateReputation`;
    console.log("Sending request to:", url);  // 添加日志
    fetch(url, requestOptions)
        .then((response) => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then((result) => {
          const { code, msg } = result;
          if (code === 0) {
            this.$message.success("Reputation Score Added Successfully!", 1);
          } else {
            this.$message.error(msg);
          }
        })
        .catch((error) => {
          this.$message.error("Failed to update reputation score. API call failed.");
          console.log(error);
        });
  },
};
</script>

<style></style>